package com.woniuxy.movice.handler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.movice.dto.User;
import com.woniuxy.movice.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@Data
@Controller
@RequestMapping("/user")
@Api("用户信息")
public class UserController {
	
	@Resource
	private UserService userService;
	
	@ApiOperation(value="通过账号，查询用户信息",notes="传入账号")
	@RequestMapping(value="/showUserInfo",method=RequestMethod.POST)
	@ResponseBody
	public User showUserInfo(String account){
		Calendar calendar = Calendar.getInstance();
		User user = userService.findUserInfoByAccount(account);
		try {
			if(user.getBirth()!=null){
				calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(user.getBirth()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user.setYear(calendar.get(Calendar.YEAR));
		user.setMonth(calendar.get(Calendar.MONTH)+1);
		user.setDate(calendar.get(Calendar.DATE));
		return user;
	}
	
	@ApiOperation(value="通过用户账号，更新用户信息",notes="传入用户账号")
	@RequestMapping(value="/updateUser",method=RequestMethod.POST)
	@ResponseBody
	public int updateUser(User user){
		return userService.updateUser(user);
	}
	
	@ApiOperation(value="从session中取出用户信息")
	@RequestMapping(value="/getUser",method=RequestMethod.GET)
	@ResponseBody
	public User getUser(HttpServletRequest request){
		User user = null;
		Object object = request.getSession().getAttribute("user");
		if(object !=null){
			user = (User) object;
		}
		return user;
	}
	
	@ApiOperation(value="从session中移除用户信息")
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	@ResponseBody
	public int logout(HttpServletRequest request){
		request.getSession().removeAttribute("user");
		return 1;
	}
	
	@ApiOperation(value="模拟登陆成功，向session中存入用户信息")
	@RequestMapping(value="/setUser",method=RequestMethod.GET)
	@ResponseBody
	public String addUser(HttpServletRequest request){
		User user = userService.findUserInfoByAccount("18812341235");
		request.getSession().setAttribute("user", user);
		return user.toString();
	}
	
}
